'use strict';

const Service = require('egg').Service;

class CommentService extends Service {

  /**
   * 添加评论
   */
  async addComments(dataId, query, modelClassName) {
    const { Comments } = this.ctx.model;
    const ModelClass = this.ctx.model[modelClassName]
    const {icon, name, mention, content, userId, superCommentId} = query
    const model = await new Comments({
      icon, name, mention, content, userId,
      date: new Date(),
    }).save();
    const classModel = superCommentId ? Comments : ModelClass
    await classModel.addComments(superCommentId || dataId, model._id)
  }

  /**
   * 删除评论
   */
  async deleteComments(id, { dataId, superCommentId }, modelClassName) {
    const ModelClass = this.ctx.model[modelClassName]
    // 获取当前数据
    const { Comments } = this.ctx.model;
    const currentModel = await Comments.findWithId(id)
    if (!currentModel) {
      throw new Error('当前评论未查到')
    }
    if (currentModel.children.length > 0) {
      throw new Error('必须先删除所有子评论')
    }
    const { OAuthUserInfo } = this.ctx.session;
    const { userId } = OAuthUserInfo || {}
    // 校验是否有权限删除
    if (this.ctx.isLogin() || userId === currentModel.userId) {
      // 先删除父节点数据
      if (superCommentId) {
        await Comments.removeSubComments(superCommentId, id)
      } else {
        await ModelClass.removeComments(dataId, id)
      }
      await Comments.deleteWithId(id);
    } else {
      throw new Error('没有权限删除')
    }
  }
}

module.exports = CommentService;
